import Koa from 'koa';
import bodyParser from 'koa-bodyparser';
import serve from 'koa-static';
import path from 'path';
import router from './routes';
import { testConnection } from './config/database';

const app = new Koa();

// 使用中间件
app.use(bodyParser());

// 静态文件服务
app.use(serve(path.join(__dirname, 'public')));

// 使用路由中间件
app.use(router.routes()).use(router.allowedMethods());

// 错误处理
app.on('error', (err, ctx) => {
  console.error('Server error', err, ctx);
});

const PORT = process.env.PORT || 3000;

// 启动服务器前先测试数据库连接
testConnection().then(() => {
  app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
    console.log(`Visit http://localhost:${PORT} to test file upload`);
  });
});
